import java.sql.*;

/**
 * Created by WeiZehao on 16/12/2.
 * This class is for Database.
 */

public class Database
{
    private static final String url = "jdbc:mysql://localhost:3306/emailData?" +
            "useUnicode=true&characterEncoding=utf-8&useSSL=false";
    private static final String address1 = "whu_weizehao@sina.com";
    private static final String address2 = "whu_weizehao@163.com";
    private static final String address3 = "whu_weizehao@126.com";
    private static final String address4 = "wzh314403865@163.com";

    private Connection con;
    private ResultSet resultSet;
    private PreparedStatement preStmt;

    /**
     * connect to database
     */
    public Database()
    {
        try
        {
            Class.forName("com.mysql.jdbc.Driver");
            con = DriverManager.getConnection(url,"root","");
        }
        catch (Exception e)
        {
            e.printStackTrace();
        }
    }

    /**
     * close connection
     */
    public void close()
    {
        try
        {
            con.close();
            preStmt.close();
        }
        catch (SQLException e)
        {
            e.printStackTrace();
        }
    }

    public void insertData()
    {
        String sql = "INSERT INTO email(address) VALUES(?)";
        try
        {
            preStmt = con.prepareStatement(sql);
            preStmt.setString(1,address1);
            preStmt.executeUpdate();

            preStmt = con.prepareStatement(sql);
            preStmt.setString(1,address2);
            preStmt.executeUpdate();

            preStmt = con.prepareStatement(sql);
            preStmt.setString(1,address3);
            preStmt.executeUpdate();

            preStmt = con.prepareStatement(sql);
            preStmt.setString(1,address4);
            preStmt.executeUpdate();
        }
        catch (Exception e)
        {
            e.printStackTrace();
        }
    }

    public ResultSet getData()
    {
        String sql = "SELECT address FROM email";
        try
        {
            preStmt = con.prepareStatement(sql);
            resultSet = preStmt.executeQuery();
            return resultSet;
        }
        catch (SQLException e)
        {
            e.printStackTrace();
        }
        return resultSet;
    }
}
